<?php

class License
{
	private $db;
	
	public function __construct()
	{
		global $config;
		$this->db = new myMysql( $config['db_host'],$config['db_user'],$config['db_pwd'],$config['db_name'],$config['db_char'] );
		return ;
	}
	
	public function checkLicense( $license,$url,$product_code )
	{
		$domain = $this->getDomain( $url );
		$this->db->query( "select * from ls_license where license = '{$license}' and website='{$domain}' and product_code='{$product_code}'" );		
		$license = $this->db->fetch_array();
		if( $license ){			
			$expired_time = strtotime("+{$license['days']} day",strtotime(substr( $license['create_date'],0,strpos( $license['create_date'],' ' ) )));
			if( $expired_time>=time() ){
				return ceil(($expired_time-time())/(3600*24));
			}
		}else return 0;
			
	}
	
	public function licenseExist( $domain,$product_code )
	{
		$domain = $this->getDomain( $domain );
		$this->db->query( "select * from ls_license where website = '{$domain}' and product_code='{$product_code}'" );		
		$license = $this->db->fetch_array();
		return $license;
	}
	
	public function applyLicense( $domain,$product_code )
	{
		$domain = $this->getDomain( $domain );
		$license = $this->createLicense( $domain );
		$date = date('Y-m-d H:i:s',time());
		$this->db->query( "insert into ls_license( license,website,product_code,create_date,days ) values('{$license}','{$domain}','{$product_code}','{$date}',0)" );
		return $license;
	}
	
	private function getDomain( $url )
	{
		if( eregi('^http.*',$url) ){
			preg_match_all('/^https?:\/+([^\/]*)\/?/i',$url,$result);
			return $result[1][0];
		}else return $url;
	}
	
	private function createLicense( $domain )
	{
		return md5( $domain.time() );
	}
}